//
//  IPAServices.swift
//
//
//  Created by tank on 9/3/24.
//

import Foundation
import StoreKit

class IPAService {
    
    init() {
        if #available(iOS 15.0, *) {
            Task {
                await listenForTransactions()
            }
        }
    }
    
    @available(iOS 15.0, *)
    func product(id: String) async throws -> Product? {
        let products = try await Product.products(for: [id])
        
        return products.first
    }
    
    @available(iOS 15.0, *)
    func purchase(product: Product) async throws -> Product.PurchaseResult {
        let result = await try product.purchase()
        
        switch result {
        case .success(let transaction):
            await handleTransaction(transaction)
            
        case .userCancelled:
            // 用户取消了购买
            print("用户取消了购买")
        
        case .pending:
            // 购买处于待处理状态
            print("购买处于待处理状态")
        }
        
        return result
    }
    
    // 监听交易更新
    @available(iOS 15.0, *)
    func listenForTransactions() async {
        for await result in Transaction.updates {
            await handleTransaction(result)
        }
    }

        // 处理交易逻辑
    @available(iOS 15.0, *)
    func handleTransaction(_ transactionResult: VerificationResult<Transaction>) async {
        switch transactionResult {
        case .verified(let transaction):
            // 处理已验证的交易
            print("处理已验证的交易: \(transaction.id), 商品ID: \(transaction.productID)")
            // 根据需要解锁功能或通知用户
            
            transaction.appAccountToken
            
            transaction.originalID
            
            transaction.id
            
            // 完成交易
            await transaction.finish()
            
        case .unverified(let transaction, let error):
            // 处理未验证的交易
            print("未验证的交易: \(transaction.id), 错误: \(error.localizedDescription)")
        }
    }
}
